package com.water.camera.adapter;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.water.camera.bean.MediaData;
import com.water.camera.fragment.ImgFragment;
import com.water.camera.fragment.VideoFragment;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class PhotoAdapter extends FragmentStateAdapter {

    List<MediaData> list;
    boolean video;

    HashSet<Integer> set = new HashSet<>();

    public PhotoAdapter(@NonNull FragmentActivity fragmentActivity, List<MediaData> list, boolean video) {
        super(fragmentActivity);
        this.list = list;
        this.video = video;
        updateSet(list);
    }

    private void updateSet(List<MediaData> list) {
        if (list != null && !list.isEmpty()) {
            for (MediaData item : list) {
                set.add(item.hashCode());
            }
        }
    }

    public void append(List<MediaData> tmp) {
        if (tmp == null || tmp.isEmpty()) {
            return;
        }
        updateSet(tmp);
        if (list == null) {
            list = new ArrayList<>();
        }
        int start = list.size();
        list.addAll(tmp);
        notifyItemRangeInserted(start, tmp.size());
    }

    public void remove(int i) {
        MediaData item = list.remove(i);
        set.remove(item.hashCode());
        notifyItemRemoved(i);
    }

    @Override
    public long getItemId(int position) {
        return list.get(position).hashCode();
    }

    @Override
    public boolean containsItem(long itemId) {
        return set.contains((int) itemId);
    }

    public MediaData getData(int i) {
        return list.get(i);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        if (video) {
            return new VideoFragment().setVideo(list.get(position), position);
        }
        ImgFragment f = new ImgFragment();
        f.setPath(list.get(position));
        return f;
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }
}
